<?php

class CMember extends Zend_Db_Table{
	
	protected $_name;
	
	protected $_primary;
	
	public function _setup(){
		
		$this->_name=R_PRE."members";
		
		$this->_primary="uid";
		
		parent::_setup();
		
	}
	
	public function create($data,$memberData=null){

		$uid=$this->insert($data);
		
		return $uid;
		
	}
	
	public function getUserCounts($fieldArray=null){
		
		$db=$this->getAdapter();
		
		$select=$db->select();
		
		$select->from($this->_name,'COUNT(*)');
		
		if($fieldArray!=null){
		
			foreach ($fieldArray as $field => $value){
				
				$where = $db->quoteInto("$field = ?", $value);
				
				$select->where($where);
				
			}
		
		}
		
		return $db->fetchOne($select);
		
	}
	
	public function getUserDetails($fieldArray=null){
		
		$db=$this->getAdapter();
		
		$whereString=null;
		
		if($fieldArray!=null){
		
			$where=array();
			
			foreach ($fieldArray as $field => $value){
				
				$where[]= $db->quoteInto("$field = ?", $value);
				
			}
			
			$whereString=join(' AND ',$where);
		
		}
		
		$row=$this->fetchAll($whereString);
		
		if($row!=null){
	
			return $row->toArray();
			
       	}else{
       		
       		return array();
       		
       	}
		
	}
	
	public function getAllUsers($from,$counts,$fieldArray=null){
		
		$db=$this->getAdapter();
		
		$select=$db->select();
		
		$select->from($this->_name,'*');
		
		if($fieldArray!=null){
			
			foreach ($fieldArray as $field => $value){
				
				$where = $db->quoteInto("$field = ?", $value);
				
				$select->where($where);
				
			}
			
		}
		
		$select->order("uid DESC");
		
		$select->limit($counts, $from);
		
		return $db->fetchAll($select);
		
	}
	
	public function getAllUsersSort($from,$counts,$fieldArray=null)
	{
		$db=$this->getAdapter();
		$select=$db->select();
		$select->from($this->_name,'*');
		if($fieldArray!=null){
			foreach ($fieldArray as $field => $value){
				$where = $db->quoteInto("$field = ?", $value);
				$select->where($where);
			}
		}
		$select->order("integral DESC");
		$select->limit($counts, $from);
		return $db->fetchAll($select);
	}
	
	public function updateUserDetail($valueArray,$fieldArray){
		
		$db=$this->getAdapter();
		
		$where=array();
		
		foreach ($fieldArray as $field => $value){
			
			$where[]= $db->quoteInto("$field = ?", $value);
			
		}
		
		$where=join(' AND ',$where);
		
		return $this->update($valueArray,$where);
		
	}
	
	public function updateUser($row, $uid)
	{
		$db = $this->getAdapter();
		$where = $db->quoteInto('uid = ?', $uid);
		return $this->update($row, $where);
	}
	
	
	public function login($username,$userpass,$member_type="buyer"){

		$db=$this->getAdapter();
		
		$userArray=$this->getUserDetails(array('lower(username)'=>strtolower($username)));
		
		$time=$userArray[0]['reg_time'];
		
		$ip=$userArray[0]['reg_ip'];
		
		require_once MY_ROOT.'/chelpers/User.php';
		
		$helper=new Zend_Controller_Action_Helper_User();
		
		$md5Password=$helper->encodePassword($userpass,$userArray[0]['username'],$time,$ip);		
		
		$where = $db->quoteInto('lower(username) = ?', strtolower($username))
       				. $db->quoteInto(' AND userpass = ?', $md5Password)
       				. $db->quoteInto(' AND member_type = ?', $member_type);

       	$row=$this->fetchRow($where);
       	
       	if($row!=null){
       		$buyer = new CBuyer();
       		$arr = $row->toArray();
       		$buyerArr = $buyer->getUserDetails(array('uid'=>$arr['uid']));
       		$arr['nick_name'] = $buyerArr[0]['nick_name'];		
			return $arr;
			
       	}else{
       		
       		return array();
       		
       	}
		
	}
	
	public function isAdmin($moduleName,$controllerName){
		
		$uid=$_COOKIE[COOKIE_PRE.'uid'];
		
		$userpass=$_COOKIE[COOKIE_PRE.'userpass'];
		
		$member_type=$_COOKIE[COOKIE_PRE.'member_type'];
		
		if($uid==''||$userpass==''||$member_type==''){
			
			return false;
			
		}
		
       	$acl=Zend_Registry::get('acl');

      	if(!$acl->isAllowed($member_type, $moduleName)){
      			
      		return false;
      			
      	}
		
		Zend_Session::start();
		
		$sellerSession=new Zend_Session_Namespace('member');
		
		if($sellerSession->userCode!=$userpass){

			return false;
			
		}
		
		$db=$this->getAdapter();
		
		$authAdapter = new Zend_Auth_Adapter_DbTable($db, $this->_name, 'uid', 'userpass');

		$authAdapter->setIdentity($uid)
           	 		->setCredential($userpass);
        		
        $result = $authAdapter->authenticate();
        
        if($result->isValid()){

        	return true;
        	
        }else{

        	return false;
        	
        }	
		
		
	}
	
	public function isUser($moduleName,$controllerName){
		Zend_Session::start();
		
		$sellerSession=new Zend_Session_Namespace('member');
		$uid='';
		
		$userpass='';
		
		$member_type='';
		
		if(isset($sellerSession->uid)){
		
			$uid=$sellerSession->uid;
			
		}
		if(isset($sellerSession->userpass)){
			
			$userpass=$sellerSession->userpass;
		
		}
		if(isset($sellerSession->member_type)){
			
			$member_type=$sellerSession->member_type;
			
		}
		
//		if($uid==''||$userpass==''||$member_type==''){
//			
//			return false;
//			
//		}

		if($uid=='' || $member_type==''){
			
			return false;
			
		}
		
       	$acl=Zend_Registry::get('acl');

      	if(!$acl->isAllowed($member_type, $moduleName)){
      			
      		return false;
      			
      	}
		
		
		
		if($sellerSession->userCode!=$userpass){

			return false;
			
		}
		
		$db=$this->getAdapter();
		
		$authAdapter = new Zend_Auth_Adapter_DbTable($db, $this->_name, 'uid', 'userpass');

		$authAdapter->setIdentity($uid)
           	 		->setCredential($userpass);
        		
        $result = $authAdapter->authenticate();
        
        if($result->isValid()){

        	return true;
        	
        }else{

        	return false;
        	
        }
        	
		
	}
	
	public function getAllUid(){
		
		$db=$this->getAdapter();
		
		$select=$db->select();
		
		$select->from($this->_name,'uid');
		
		return $db->fetchAll($select);
		
	}
	
	public function getAllUserDetails($fieldArray){
		
		$db=$this->getAdapter();
		
		$select=$db->select();
		
		$select->from($this->_name,$fieldArray);
		
		return $db->fetchAll($select);
		
	}
	
	public function updateCoupon($coupon,$uid,$isPlus){
		
		$db=$this->getAdapter();
		
		try{
			
			if($isPlus){

				$db->query("UPDATE $this->_name SET my_coupon=my_coupon+$coupon WHERE uid='$uid'");
				
			}else{
				
				$db->query("UPDATE $this->_name SET my_coupon=my_coupon-$coupon WHERE uid='$uid'");
				
			}
			
			return true;
		
		}catch(Exception $e){
			
			return $e->getMessage();
			
		}
		
		return false;
			
	}
	
	public function getUsername($fieldArray){
		
		$db=$this->getAdapter();
		
		$whereString=null;
		
		if($fieldArray!=null){
		
			$where=array();
			
			foreach ($fieldArray as $field => $value){
				
				$where[]= $db->quoteInto("$field = ?", $value);
				
			}
			
			$whereString=join(' AND ',$where);
		
		}
		
		$select=$db->select();
		
		$select->from($this->_name,'username');
		
		$select->where($whereString);
		
		return $db->fetchAll($select);
		
	}

        //根据用户UID返回用户积分值
        public function getintegral($uid){
            
		$db=$this->getAdapter();

		$select=$db->select();

		$select->from($this->_name,'integral');

                $select->where('uid = ? ',$uid);
		return $db->fetchAll($select);
        }

        //更新积分
	public function updateIntegral($integral,$uid,$action = 0){

		$db=$this->getAdapter();

		try{

			if($action){

				$db->query("UPDATE $this->_name SET integral=integral+$integral WHERE uid='$uid'");

			}else{

				$db->query("UPDATE $this->_name SET integral=integral-$integral WHERE uid='$uid'");

			}

			return true;

		}catch(Exception $e){

			return $e->getMessage();

		}

		return false;

	}
	
	//是否绑定 帐号
	public function isBind($appId, $appType) 
	{
		 switch ($appType) {
		 	case 'twitter':
		 		$col = 'twitter_id';
		 		break;
		 	case 'facebook':
		 		$col = 'facebook_id';
		 		break;
		 	default:
		 		return false;
		 }
		 
		 $row = $this->fetchRow(array($col . ' = ?'=>$appId));
		 $arr = array();
		 if ($row) {	
		 	$buyer = new CBuyer();
       		$arr = $row->toArray();
       		$buyerArr = $buyer->getUserDetails(array('uid'=>$arr['uid']));
       		$arr['nick_name'] = $buyerArr[0]['nick_name'];		
		 }
		 return $arr;
	}
	
	/**
	 * 
	 * 绑定帐号
	 * @param string $username
	 * @param bigint $appId
	 * @param string $type
	 */
	public function bindAccount($username, $appId, $type)
	{
		$row = $this->fetchRow(array('username = ?'=>$username));		
		if ($row) {
			$appSession = new Zend_Session_Namespace('app');
			switch ($type) {
				case 'twitter':
					if ($row->twitter_id > 0)
						return false;
					$array = array('twitter_id'=>$appSession->id, 'reg_from'=>'twitter');
					break;
				case 'facebook':
					if ($row->facebook_id > 0)
						return false;
					$array = array('facebook_id'=>$appSession->id, 'reg_from'=>'facebook');
					break;
				default:
					return false;
			}
			$db = $this->getAdapter();
			$where = $db->quoteInto('username = ?', $username);
			return $this->update($array,$where);
		} else {
			return false;
		}
	}
	/**
	 * 获取最近注册的用户，查看订单情况
	 */
	public function getRegOrder($from,$to,$status){
		$db=$this->getAdapter();
		$sql ="select m.uid,m.username,m.reg_time,m.member_type,f.orderid,f.flid from zcshop_members m left join zcshop_orders f on m.uid=f.uid where m.reg_time>=$from and m.reg_time<=$to";
		if(!empty($status)){
			$sql.=" and f.flid in (2,3,4,5,9)";
		}
		$sql.=" group by m.uid";
		$rows = $db->fetchAll($sql);
		return $rows;
	}
}